package com.wxw.BaseLibrary.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wxw.BaseLibrary.R;

/**
 *
 * @author david
 * @date 2020-03-18
 */
public abstract class BaseDialog implements IDialog {
    protected Context parentActivity;
    protected Dialog dialog;
    protected View layout;
    protected String title = "Title";
    protected boolean cancelable = false;
    protected int widthOffset = 0;
    protected int tvTitleResourceID = 0;
    protected int dialogThemeId = 0;
    protected int dialogAnimationId = 0;

    /**
     * 初始化对话框
     * @return
     */
    public abstract View initView();

    @Override
    public void show() {
        if (layout == null) {
            initView();
        }
        if(dialog ==null) {
            if (dialogThemeId != 0) {
                dialog = new Dialog(parentActivity, dialogThemeId);
            } else {
                dialog = new Dialog(parentActivity);
            }
        }
        setDialogAnimation(dialog, dialogAnimationId);

        dialog.setCancelable(cancelable);
        int width = ((Activity)parentActivity).getWindowManager().getDefaultDisplay().getWidth();

        dialog.setContentView(layout, new LinearLayout.LayoutParams(width - widthOffset, LinearLayout.LayoutParams.MATCH_PARENT));
        dialog.show();

    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public boolean isCancelable() {
        return cancelable;
    }

    public void setCancelable(boolean cancelable) {
        this.cancelable = cancelable;
    }

    public void showKeyboard(EditText editText) {
        if (editText != null) {
            //设置可获得焦点
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            //请求获得焦点
            editText.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager)parentActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(editText, 0);
        }
    }

    public static void setDialogAnimation(Dialog dialog, int animationId) {
        Window window = dialog.getWindow();
        //设置窗口弹出动画
        window.setWindowAnimations(animationId);
        //设置对话框背景为透明
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams wl = window.getAttributes();
        //根据x，y坐标设置窗口需要显示的位置
        //x小于0左移，大于0右移
        wl.x = 0;
        //y小于0上移，大于0下移
        wl.y = 0;
//            wl.alpha = 0.6f; //设置透明度
//            wl.gravity = Gravity.BOTTOM; //设置重力
        window.setAttributes(wl);
    }
}